﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using Lottery.Herper;
using Lottery.MediaData.Core;

namespace Lottery.MediaData.UI {
    /// <summary>
    /// 指定过滤 主界面
    /// </summary>
    public partial class DoFilterForm : Form {

        private string m_qiShu;

        public DoFilterForm(string qiShu)
            : this() {
            m_qiShu = qiShu;

            this.Text = string.Format("指定过滤 {0}期", qiShu);
            labelIndexInfo.Text = string.Format("足彩期数: {0}", qiShu);

            labelHZFilterName.Text = string.Empty;
        }

        private DoFilterForm() {
            InitializeComponent();
        }

        FTCellData m_data = null;

        /// <summary>
        /// 投注
        /// </summary>
        List<long> m_touZhu = null;

        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);//设置此窗体句柄的窗体为活动窗体

        private void buttonLoadFilterTable_Click(object sender, EventArgs e) {
            // 调入过滤表(Excel)
            //ofdExcel.InitialDirectory = DataHelper.ExcelPath_14;
            if (ofdExcel.ShowDialog() != DialogResult.OK) {
                return;
            }

            var fileName = ofdExcel.FileName;
            labelFileName.Text = string.Format("过滤表文件:{0}", fileName);

            WaitForm form = new WaitForm();
            form.SetInfo("正在导入过滤表Excel文件，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                ETHelper.Import(fileName, out m_data);
            };

            bw.RunWorkerCompleted += (a, b) => {
                SetForegroundWindow(form.Handle);
                form.Hide();
                form.Close();
                if (b.Error == null) {
                    grid.SetGridData(m_data);
                    grid.SetErrorCellColor();
                    grid.HideLastTwoCols();
                    ShowOKInfo("成功导入过滤表数据");
                    grid.Focus();
                } else {
                    ShowErrorInfo(b.Error.Message);
                }
            };
            bw.RunWorkerAsync();
            form.ShowDialog();

        }

        private void buttonLoadSet_Click(object sender, EventArgs e) {
            // 调入投注数
            if (m_touZhu != null && m_touZhu.Count != 0) {
                if (this.ShowYesNoInfo("当前投注表里面已经有数据了，请确认是否重新调入投注表") != DialogResult.Yes) {
                    grid.Focus();
                    return;
                }
            }

            if (ofdText.ShowDialog() != DialogResult.OK) {
                grid.Focus();
                return;
            }

            labelFilterName.Text = string.Format("投注表文件：{0}", ofdText.FileName);

            WaitForm form = new WaitForm();
            form.SetInfo("正在调入投注表，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                ExecLoad();
            };
            bw.RunWorkerCompleted += (a, b) => {
                pageList.DataSource = m_touZhu;
                listBoxCheck.Items.Clear();
                SetCountInfo();
                form.Hide();
                form.Close();
                if (b.Error == null)
                    ShowOKInfo("成功调入投注表");
                else
                    ShowErrorInfo(b.Error.Message);
                grid.Focus();
            };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private void ExecLoad() {
            var fileName = ofdText.FileName;

            var list = new List<long>();
            using (var s = File.OpenText(fileName)) {
                while (!s.EndOfStream) {
                    var str = s.ReadLine();
                    if (str.Length != 14) {
                        continue;
                    }

                    list.Add(FTHelper.StrToLong(str));
                }
            }

            m_touZhu = list;
        }

        private void SetCountInfo() {
            labelInfo.Text = string.Format("共 {0} 注", m_touZhu == null ? 0 : m_touZhu.Count);
        }

        private void ShowOKInfo(string info) {
            MessageBox.Show(this, info, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ShowErrorInfo(string info) {
            MessageBox.Show(this, info, "提示",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void buttonDo_Click(object sender, EventArgs e) {
            // 开始过滤
            if (m_data == null || m_data.RowCount == 0) {
                this.ShowInfo("没有过滤表数据");
                grid.Focus();
                return;
            }
            if (m_touZhu == null || m_touZhu.Count == 0) {
                this.ShowInfo("没有投注表数据");
                grid.Focus();
                return;
            }

            if (this.ShowYesNoInfo("请确认是否开始过滤") != DialogResult.Yes) {
                grid.Focus();
                return;
            }

            var beginTime = DateTime.Now;
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                ExecFilter();
            };

            WaitForm form = new WaitForm();
            form.SetInfo("正在过滤，请稍等...");
            bw.RunWorkerCompleted += (a, evn) => {
                form.Hide();
                form.Close();
                pageList.DataSource = m_touZhu;
                listBoxCheck.Items.Clear();
                SetCountInfo();
                if (evn.Error == null) {
                    var endTime = DateTime.Now;
                    var delta = endTime - beginTime;
                    ShowOKInfo(string.Format("过滤完成\n\n耗时{0}", delta));
                } else
                    ShowErrorInfo(evn.Error.Message);

                grid.Focus();
            };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private void ExecFilter() {
            var ft = m_data.CreateFT();

            if (ft.RowCount == 0) {
                return;
            }

            m_touZhu = FTHelper.DoFilter(ft, m_touZhu);
        }

        private void DoFilterForm_Shown(object sender, EventArgs e) {
            labelInfo.Text = string.Empty;
            labelFileName.Text = string.Empty;
            labelFilterName.Text = string.Empty;
            grid.InitGrid();
            grid.AutoResizeColumns();
            grid.HideLastTwoCols();
        }

        private void buttonAll_Click(object sender, EventArgs e) {
            if (this.ShowYesNoInfo("请确认是否生成投注表全集") != DialogResult.Yes) {
                grid.Focus();
                return;
            }

            labelFilterName.Text = "投注表文件：全集";
            WaitForm form = new WaitForm();
            form.SetInfo("正在生成投注表全集，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                m_touZhu = FTHelper.GenAllSet();
            };
            bw.RunWorkerCompleted += (a, b) => {
                if (b.Error == null) {
                    pageList.DataSource = m_touZhu;
                    listBoxCheck.Items.Clear();
                    SetCountInfo();
                    form.Close();
                } else
                    ShowErrorInfo(b.Error.Message);
            };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private void buttonSave_Click(object sender, EventArgs e) {
            if (m_touZhu == null || m_touZhu.Count == 0) {
                this.ShowInfo("没有投注记录");
                grid.Focus();
                return;
            }

            var formOption = new SaveTouZhuOptionForm();
            if (formOption.ShowDialog() != DialogResult.OK) {
                grid.Focus();
                return;
            }

            int countPerLine = formOption.CountPerLine;

            WaitForm form = new WaitForm();
            form.SetInfo("正在保存投注表，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                DoSave(m_touZhu, countPerLine);
            };
            bw.RunWorkerCompleted += (a, b) => {
                form.Hide();
                form.Close();
                if (b.Error == null) {
                    labelFilterName.Text = string.Format("投注表文件: {0}", m_savedFileName);
                    ShowOKInfo("成功保存投注记录");
                } else
                    ShowErrorInfo(b.Error.Message);
                grid.Focus();
            };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private string m_savedFileName;
        private void DoSave(List<long> data, int countPerLine) {
            m_savedFileName = FTHelper.SaveTouZhu(m_qiShu, data, countPerLine);
        }

        private void buttonOpenDir_Click(object sender, EventArgs e) {
            var pt = new Point(0, buttonOpenDir.Height);
            contextMenuStrip1.Show(buttonOpenDir, pt);
        }

        private void buttonCheck_Click(object sender, EventArgs e) {
            if (m_data == null || m_data.RowCount == 0) {
                this.ShowInfo("没有过滤表数据，无法模拟开奖");
                grid.Focus();
                return;
            }

            var form = new SimulationForm();
            form.Numbers = DataHelper.LoadNumbers(m_qiShu);

            if (form.ShowDialog() == DialogResult.OK) {
                var numbers = form.Numbers;
                //保存奖号
                DataHelper.SaveNumbers(m_qiShu, numbers);

                DataHelper.DoSimulation(numbers, m_data);
                grid.ShowLastTwoCols();
                grid.SetGridData(m_data);
                grid.SetErrorCellColor();
                grid.AutoResizeColumns();
            }
        }

        private void buttonCheck2_Click(object sender, EventArgs e) {
            if (m_touZhu == null || m_touZhu.Count == 0) {
                this.ShowInfo("没有投注表数据，无法模拟开奖");
                grid.Focus();
                return;
            }

            var form = new SimulationForm();
            form.Numbers = DataHelper.LoadNumbers(m_qiShu);

            if (form.ShowDialog() == DialogResult.OK) {
                var numbers = form.Numbers;
                //保存奖号
                DataHelper.SaveNumbers(m_qiShu, numbers);

                var result = DataHelper.DoSimulationForTouZhu(numbers, m_touZhu);
                listBoxCheck.Items.Clear();
                foreach (var item in result) {
                    listBoxCheck.Items.Add(item);
                }

                this.ShowInfo("模拟开奖完成");
                listBoxCheck.Focus();
            }
        }

        private void menuItem09_Click(object sender, EventArgs e) {
            System.Diagnostics.Process.Start("explorer.exe", FTHelper.TouZhuPath_09);
            grid.Focus();
        }

        private void menuItem14_Click(object sender, EventArgs e) {
            System.Diagnostics.Process.Start("explorer.exe", FTHelper.TouZhuPath_14);
            grid.Focus();
        }

        private List<HZLine> m_hzData;

        private void buttonLoadHZFilter_Click(object sender, EventArgs e) {
            // 调入过滤表(Excel)
            if (ofdExcel.ShowDialog() != DialogResult.OK) {
                return;
            }

            var fileName = ofdExcel.FileName;
            labelHZFilterName.Text = fileName;

            WaitForm form = new WaitForm();
            form.SetInfo("正在导入过滤表Excel文件，请稍等...");

            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                m_hzData = HZHelper.LoadFromExcel(fileName);
            };
            bw.RunWorkerCompleted += (a, b) => {
                SetForegroundWindow(form.Handle);
                form.Hide();
                form.Close();
                if (b.Error == null) {
                    SetHzData();
                    ShowOKInfo("成功导入过滤表数据");
                    listBoxIndex.Focus();
                } else {
                    ShowErrorInfo(b.Error.Message);
                }
            };

            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private void SetHzData() {
            hzInput.ClearData();
            listBoxIndex.Items.Clear();
            foreach (var item in m_hzData) {
                listBoxIndex.Items.Add(item.Index);
            }
            if (listBoxIndex.Items.Count > 0) {
                listBoxIndex.SelectedIndex = 0;
            }
        }

        private void listBoxIndex_SelectedIndexChanged(object sender, EventArgs e) {
            if (listBoxIndex.SelectedIndex == -1) {
                return;
            }

            var item = m_hzData[listBoxIndex.SelectedIndex];
            hzInput.SetAB(item.A, item.B);
            for (int i = 0; i < 14; i++) {
                var hz = item[i];
                hzInput[i].Set310(hz.Three, hz.One, hz.Zero);
            }
        }

        private void button2_Click(object sender, EventArgs e) {
            // 和值 开始过滤
            if (m_hzData == null || m_hzData.Count == 0) {
                this.ShowInfo("没有过滤表数据");
                listBoxIndex.Focus();
                return;
            }
            if (m_touZhu == null || m_touZhu.Count == 0) {
                this.ShowInfo("没有投注表数据");
                listBoxIndex.Focus();
                return;
            }

            // 查检过滤表数据
            foreach (var item in m_hzData) {
                if (string.IsNullOrEmpty(item.A)) {
                    var info = string.Format("序号为{0}的下限没有填写", item.Index);
                    this.ShowInfo(info);
                    return;
                }
                if (string.IsNullOrEmpty(item.B)) {
                    var info = string.Format("序号为{0}的上限没有填写", item.Index);
                    this.ShowInfo(info);
                    return;
                }
                for (int i = 0; i < 14; i++) {
                    var hz = item[i];
                    var isOK = hz.Three == string.Empty && hz.One == string.Empty
                        && hz.Zero == string.Empty;
                    isOK = isOK || (hz.Three != string.Empty && hz.One != string.Empty &&
                        hz.Zero != string.Empty);
                    if (!isOK) {
                        var info = string.Format("序号为{0} 第{1}场的数据没有填写完整", item.Index, i + 1);
                        this.ShowInfo(info);
                        return;
                    }
                }
            }

            if (this.ShowYesNoInfo("请确认是否开始过滤") != DialogResult.Yes) {
                listBoxIndex.Focus();
                return;
            }

            var beginTime = DateTime.Now;
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += (a, b) => {
                ExecHZFilter();
            };

            WaitForm form = new WaitForm();
            form.SetInfo("正在过滤，请稍等...");
            bw.RunWorkerCompleted += (a, evn) => {
                form.Hide();
                form.Close();
                pageList.DataSource = m_touZhu;
                listBoxCheck.Items.Clear();
                SetCountInfo();
                if (evn.Error == null) {
                    var endTime = DateTime.Now;
                    var delta = endTime - beginTime;
                    ShowOKInfo(string.Format("过滤完成\n\n耗时{0}", delta));
                } else
                    ShowErrorInfo(evn.Error.Message);

                hzInput.Focus();
            };
            bw.RunWorkerAsync();
            form.ShowDialog();
        }

        private void ExecHZFilter() {
            m_touZhu = HZHelper.DoFilter(m_hzData, m_touZhu);
        }
    }
}
